#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <vector>

using namespace cv;
using namespace std;

int main()
{
    //打开图像
    Mat image = imread("../orange.jpg");
	//将BGR格式转成HSV格式
    Mat HSV;
	cvtColor(image,HSV,CV_BGR2HSV_FULL);
    //分离HSV中的S通道
	vector<Mat> channels;
	split(HSV, channels);
	Mat S = channels.at(1); 
	//对饱和度通道进行5次腐蚀和5次膨胀
    Mat erosion1,dilation1;
    Mat kernel1 = getStructuringElement(MORPH_RECT, Size(7, 7));
    erode(S, erosion1, kernel1, Point(-1,-1), 5);
    dilate(erosion1, dilation1, kernel1, Point(-1,-1), 5);
    //二值化分割，阈值设为190，浮动区间为171-209
    Mat bw;
    threshold(dilation1, bw, 171, 255, CV_THRESH_BINARY);
    //对二值化图片进行4次膨胀和4次腐蚀
    Mat kernel2 = getStructuringElement(MORPH_RECT, Size(5, 5));
    Mat erosion2,dilation2;
    dilate(bw, erosion2, kernel2, Point(-1,-1), 4);
    erode(erosion2, dilation2, kernel2, Point(-1,-1), 4);
    //检测物体轮廓
    vector<vector<Point>> cnts;  
    vector<Vec4i> hier; 
    findContours(dilation2,cnts,hier,CV_RETR_EXTERNAL,CHAIN_APPROX_SIMPLE,Point());
    //将轮廓显示原图像上
    drawContours(image,cnts,0,Scalar(0,255,0),3);
    //显示结果
    imshow("Orange", image);
    imshow("Binary",erosion2);
    waitKey();
    destroyAllWindows();
    return 0;
}
